package com.rongke.redis;

import com.rongke.utils.SerializerUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.JedisCluster;


/**
 * Created by chengwenwen on 2016/11/21.
 * redis缓存
 * 采用Jedis Cluster
 */
//@Component
public class RedisClusterCache {
    //    @Autowired
    private JedisCluster jedisCluster;

    /**
     * 添加缓存数据
     *
     * @param key
     * @param obj
     * @param <T>
     * @return
     * @throws Exception
     */
    public <T> String putCache(String key, T obj) throws Exception {
        final byte[] bkey = key.getBytes();
        final byte[] bvalue = SerializerUtil.serializeObj(obj);
        return jedisCluster.set(bkey, bvalue);
    }


    /**
     * 添加缓存数据，设定缓存失效时间
     *
     * @param key
     * @param obj
     * @param expireTime
     * @param <T>
     * @throws Exception
     */
    public <T> String putCacheWithExpireTime(String key, T obj, final int expireTime) throws Exception {
        final byte[] bkey = key.getBytes();
        final byte[] bvalue = SerializerUtil.serializeObj(obj);
        String result = jedisCluster.setex(bkey, expireTime, bvalue);
        return result;
    }

    /**
     * 根据key取缓存数据
     *
     * @param key
     * @param <T>
     * @return
     * @throws Exception
     */
    public <T> T getCache(final String key) throws Exception {
        byte[] result = jedisCluster.get(key.getBytes());
        return (T) SerializerUtil.deserializeObj(result);
    }

    /**
     * 根据key删除缓存数据
     *
     * @return
     * @throws Exception
     */
    public void delCache(final String key) throws Exception {
        jedisCluster.del(key.getBytes());
    }
}
